//
//  PackageViewModel.m
//  DingDongXiChe
//
//  Created by wtjr on 2017/11/27.
//  Copyright © 2017年 xieyingze. All rights reserved.
//

#import "PackageViewModel.h"

@interface PackageViewModel()

@end


@implementation PackageViewModel

#pragma mark - Init

- (void)initialize {
    @weakify(self);
    [self.getPackageListsCommand.executionSignals.switchToLatest subscribeNext:^(NSString *resultString) {
        @strongify(self);
        [self handleSuccessResultString:resultString];
    }];
}

#pragma mark - Method

- (void)handleSuccessResultString:(NSString *)resultString {
    NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:[resultString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
    [self.packageList removeAllObjects];
    for (NSDictionary *dic in dictionary[@"packageList"]) {
        PackageModel *model = [[PackageModel alloc] initWithDictionary:dic];
        [self.packageList addObject:model];
    }
    [self.updateTableSubject sendNext:nil];
}

#pragma mark - Interface


#pragma mark - Setter


#pragma mark - Getter

/**
 获取商家套餐请求信号
 */
- (RACCommand *)getPackageListsCommand {
    if (!_getPackageListsCommand) {
        _getPackageListsCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
            return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
                
                NetworkParam *param = [NetworkParam instance];
                param.methodName = kURL_packageList;
                param.isSHowLoading = NO;
                param.paramArr = [NSMutableArray arrayWithArray:@[
                                                                  kMethod_param(@"service_uuid", self.model.service_uuid),
                                                                  kMethod_param(@"user_uuid", [UnityTool getStringValueForKey:kUSER_userId])
                                                                  ]];
                [self.request networkRequestWithNetworkParam:param completed:^(BOOL isSucess, NSString *resultString) {
                    if (isSucess) {
                        [subscriber sendNext:resultString];
                        [subscriber sendCompleted];
                    } else {
                        [subscriber sendError:[NSError errorWithDomain:resultString code:0 userInfo:nil]];
                        //[self showAlertViewWithMessage:resultString];
                        [subscriber sendCompleted];
                    }
                }];
                return nil;
            }];
        }];
    }
    return _getPackageListsCommand;
}

- (RACSubject *)updateTableSubject {
    if (!_updateTableSubject) {
        _updateTableSubject = [RACSubject subject];
    }
    return _updateTableSubject;
}

- (NSMutableArray *)packageList {
    if (!_packageList) {
        _packageList = [NSMutableArray array];
    }
    return _packageList;
}

@end
